package com.alibaba.citrus.ots.sales.plan.facade.service.statistics.stat.category;

import com.alibaba.citrus.ots.sales.plan.dto.api.request.MonthContractAndRollingCountResponse;
import com.alibaba.citrus.ots.sales.plan.dto.api.request.QueryContractByCustomerDimensionRequest;
import com.alibaba.citrus.ots.sales.plan.facade.service.SalesPlanCommonService;
import com.alibaba.citrus.ots.sales.plan.facade.service.statistics.stat.SalesPlanStatAtomAbstract;
import com.alibaba.citrus.ots.sales.plan.facade.service.statistics.stat.model.SalesPlanStatRequest;
import com.alibaba.citrus.ots.sales.plan.model.enums.ContractDataSourceEnum;
import com.alibaba.citrus.ots.sales.plan.model.enums.ContractStatDimensionEnum;
import com.alibaba.citrus.ots.sales.plan.model.enums.SalesStatBizTypeEnum;
import com.alibaba.citrus.ots.sales.plan.model.enums.StatPoolTypeEnum;
import com.alibaba.citrus.ots.sales.plan.repository.request.StatCategoryQueryRequest;
import com.alibaba.citrus.ots.sales.plan.sdo.SalesPlanSDO;
import com.alibaba.citrus.ots.sales.plan.sdo.SalesPlanStatScItemSDO;
import com.alibaba.cz.base.tool.log.Log;
import com.epoch.app.bcots.sales_plan.planscitem.dto.PlanCategoryStatCountRequest;
import com.epoch.app.bcots.sales_plan.planscitem.dto.PlanCategoryStatCountResponse;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.collections.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.CountDownLatch;
import java.util.stream.Collectors;

/**
 * @author luyi
 * @date 2021/12/2 11:47 下午
 */
public class CategoryChannelStatService extends SalesPlanStatAtomAbstract {
    private static final Log log = Log.getLogger(CategoryChannelStatService.class);

    public CategoryChannelStatService(SalesPlanStatRequest statRequest, CountDownLatch latch){
        super.statRequest = statRequest;
        super.latch = latch;
    }


    @Override
    protected void handle(SalesPlanStatRequest statRequest) {
        statChannelCategory(statRequest.getSalesPlan(),statRequest.getYear(),statRequest.getMonth());
    }

    @Override
    protected String taskName() {
        return "categoryChannelStat";
    }

    /**
     * 类目维度
     * 销售渠道类目汇总
     *
     * @param salesPlan
     */
    private void statChannelCategory(SalesPlanSDO salesPlan, String year, String month) {

        PlanCategoryStatCountRequest request = new PlanCategoryStatCountRequest();
        request.setPlanId(salesPlan.getId().toString());
        request.setPoolType(StatPoolTypeEnum.SC_ITEM.getPoolType());
        request.setBizType(SalesStatBizTypeEnum.SALES_CHANNEL.getBizType());
        PlanCategoryStatCountResponse response = planScItemService.planCategoryStatCount(request);
        if (Objects.isNull(response)) {
            return;
        }
        Integer count = response.getCount();
        if (count == null || count <= 0) {
            log.warn("SalesPlanStatServiceImpl.planCustomerCollect planCustomerAddress nothingness");
            return;
        }
        int totalPage = (count + CUSTOMER_ADDRESS_PAGE_SIZE - 1) / CUSTOMER_ADDRESS_PAGE_SIZE;
        for (int i = 1; i <= totalPage; i++) {
            StatCategoryQueryRequest queryRequest = new StatCategoryQueryRequest();
            queryRequest.setPlanId(salesPlan.getId().toString());
            queryRequest.setPoolType(StatPoolTypeEnum.SC_ITEM.getPoolType());
            queryRequest.setBizType(SalesStatBizTypeEnum.SALES_CHANNEL.getBizType());
            queryRequest.setPage(i);
            queryRequest.setSize(CUSTOMER_ADDRESS_PAGE_SIZE);
            List<SalesPlanStatScItemSDO> salesPlanStatScItemList = salesPlanScItemStatRepository.statCategory(queryRequest);
            if (CollectionUtils.isEmpty(salesPlanStatScItemList)) {
                log.error("SalesPlanStatServiceImpl.statChannelCategory.salesPlanStatScItemList is empty");
                return;
            }
            //批量查询销售渠道类目合同量，合同金额
            List<String> channelList = Lists.newArrayList();
            List<String> categoryList = Lists.newArrayList();
            for (SalesPlanStatScItemSDO salesPlanStatScItem : salesPlanStatScItemList) {
                channelList.add(salesPlanStatScItem.getBizId());
                if (!Objects.isNull(salesPlanStatScItem.getScItemCategoryId())) {
                    categoryList.add(salesPlanStatScItem.getScItemCategoryId());
                }
            }
            Map<String, MonthContractAndRollingCountResponse> collect = Maps.newHashMap();
            if (!CollectionUtils.isEmpty(categoryList)) {
                //批量查询业务单元类目合同量，合同金额
                QueryContractByCustomerDimensionRequest queryContractRequest = new QueryContractByCustomerDimensionRequest();
                queryContractRequest.setType(ContractStatDimensionEnum.SALES_CHANNEL_CATEGORY.getCode());
                queryContractRequest.setContractYear(year);
                queryContractRequest.setPlanMonth(month);
                queryContractRequest.setOrgSalesChannelCodes(channelList);
                queryContractRequest.setScItemCategoryIds(categoryList);
                queryContractRequest.setDataSource(ContractDataSourceEnum.CUSTOMER.getCode());
                List<MonthContractAndRollingCountResponse> monthContractList = contractRepository.queryQuantityListByAddressAndScItem(queryContractRequest);
                if (CollectionUtils.isNotEmpty(monthContractList)) {
                    collect = monthContractList.stream().collect(Collectors.toMap(m -> SalesPlanCommonService.getCombinationKey(m.getOrgSalesChannelCode(), m.getScItemCategoryId()), m -> m));
                }
            }
            for (SalesPlanStatScItemSDO planStatScItem : salesPlanStatScItemList) {
                planStatScItem.setPoolType(StatPoolTypeEnum.CATEGORY.getPoolType());
                planStatScItem.setBizType(SalesStatBizTypeEnum.SALES_CHANNEL.getBizType());
                //需要查合同量补充
                MonthContractAndRollingCountResponse monthContract = collect.get(SalesPlanCommonService.getCombinationKey(planStatScItem.getBizId(), planStatScItem.getScItemCategoryId()));
                setStatContractInfo(planStatScItem, monthContract);
                calculateSatisfaction(salesPlan.getStatus(), planStatScItem);
            }
            salesPlanScItemStatRepository.batchCreatePlanScItem(salesPlanStatScItemList);
        }
    }
}
